#include "../Http.hpp"
#define INF 0
#define DBG 1
#define ERR 2
#define LOG_LEVEL INF
#define LOG(level, format, ...)                                                                                        \
    do                                                                                                                 \
    {                                                                                                                  \
        if (level < INF)                                                                                               \
            break;                                                                                                     \
        time_t t = time(NULL);                                                                                         \
        struct tm *ltm = localtime(&t);                                                                                \
        char tmp[32] = {0};                                                                                            \
        strftime(tmp, 31, "%H:%M:%S", ltm);                                                                            \
        fprintf(stdout, "[%p %s %s:%d] " format "\n", (void *)pthread_self(), tmp, __FILE__, __LINE__, ##__VA_ARGS__); \
    } while (0)
#define INF_LOG(format, ...) LOG(INF, format, ##__VA_ARGS__)
#define DBG_LOG(format, ...) LOG(DBG, format, ##__VA_ARGS__)
#define ERR_LOG(format, ...) LOG(ERR, format, ##__VA_ARGS__)
class EchoServer
{
private:
    TcpServer _server;

private:
    void OnConnected(const ConnectionPtr &conn)
    {
        DBG_LOG("NEW CONNECTION:%p", conn.get());
    }
    void OnClosed(const ConnectionPtr &conn)
    {
        DBG_LOG("CLOSE CONNECTION:%p", conn.get());
    }
    void OnMessage(const ConnectionPtr &conn, Buffer &buf)
    {
        cout << buf.getReadAddr() << endl;
        conn->Send(buf.getReadAddr(), buf.getReadSpace());
        buf.moveReadPosition(buf.getReadSpace());
    }

public:
    EchoServer(int port) : _server(port)
    {
        _server.SetThreadCount(2);
        _server.EnableInactiveRelease(5);
        _server.SetClosedCallback(bind(&EchoServer::OnClosed, this,
                                       std::placeholders::_1));
        _server.SetConnectedCallback(bind(&EchoServer::OnConnected,
                                          this, std::placeholders::_1));
        _server.SetMessageCallback(bind(&EchoServer::OnMessage, this,
                                        std::placeholders::_1, std::placeholders::_2));
    }
    void Start() { _server.Start(); }
};
int main()
{
    EchoServer server(8088);
    server.Start();
    return 0;
}